/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.kamionowski.supreme.services.search.impl;

import java.util.ArrayList;
import java.util.List;
import org.kamionowski.supreme.persistence.dao.TokenDAO;
import org.kamionowski.supreme.persistence.entity.Token;
import org.kamionowski.supreme.services.search.QueryToken;
import org.kamionowski.supreme.services.search.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author soldier
 */
@Service
public class TokenServiceImpl implements TokenService{

    @Autowired
    private TokenDAO tokenDAO;
    
    @Override
    public List<QueryToken> searchForTokensMatchingQueryString(String query, Integer limit) {
        final String queryWithoutQuotes = query.replace("\"", " ");
        final String[] parts = queryWithoutQuotes.split(" ");
        final String lastPart = ' ' == queryWithoutQuotes.charAt(queryWithoutQuotes.length() - 1) ? "" : parts[parts.length - 1];
        List<Token> tokens = tokenDAO.selectTokensStartingWithOrderedByResultsCount(lastPart, limit);
        return createResultsList(tokens, query);
    }

    protected List<QueryToken> createResultsList(List<Token> tokens, String query){
        List<QueryToken> results = new ArrayList<QueryToken>(tokens.size());
        for(Token t : tokens){
            results.add(new QueryToken(t, query));
        }
        return results;
    }

    public void setTokenDAO(TokenDAO tokenDAO) {
        this.tokenDAO = tokenDAO;
    }
}
